package com.demo.monitor;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;
import org.apache.commons.io.input.TailerListenerAdapter;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class MonitorTest {

    public static void main(String[] args) throws  Exception {
        File file = new File("./1.txt");


        try {
            FileUtils.touch(file);
        } catch (IOException e) {
            //
            System.out.println("Failed to touch file");
        }
        TailerListenerAdapter listener = new TailerListenerAdapter() {
            Tailer tailer;
            int count;
            StringBuilder buf = new StringBuilder();

            @Override
            public void init(Tailer tailer) {
                this.tailer = tailer;
            }

            @Override
            public void handle(String line) {
                buf.append(line).append("\r\n");
                if(++ count % 1000 == 0) {
                    System.out.println("stop to tail....");
                    this.tailer.stop();
                }
            }

            @Override
            public void handle(Exception ex) {
                ex.printStackTrace();
                super.handle(ex);
            }

            @Override
            public void fileRotated() {
                System.out.println("文件rotated");
                super.fileRotated();
            }

            @Override
            public void fileNotFound() {
                System.out.println("文件没有找到");
                super.fileNotFound();
            }
            @Override
            public void endOfFileReached() {

                System.out.print(buf.toString());
                buf.delete(0, buf.length());
            }

        };

        Tailer tailer = new Tailer(file, listener, 5000, true);
        new Thread(tailer, "myTailer").start();

        while(true){
            Thread.sleep(100);
            FileUtils.write(file,"时间-"+ new Date() + IOUtils.LINE_SEPARATOR,true);
        }
    }
}
